package pkg

import (
	"enjoy-shop/formdata"
	"fmt"
	orderpb "gitee.com/enjoy_5/order-rpc/proto/order"
	"gitee.com/enjoy_5/spikes-rpc/client/spikes"
	pb "gitee.com/enjoy_5/spikes-rpc/proto/spikes"
	"github.com/dtm-labs/dtm/client/dtmcli"
	"github.com/google/uuid"
	"strconv"
)

// 事务

func QsFireRequest(data formdata.OrderInfo) (string, error) {
	var skuId int64
	//订单请求体

	var pr []*orderpb.OrderGoodsInfo

	for _, val := range data.Pr {
		pr = append(pr, &orderpb.OrderGoodsInfo{
			GoodsId:  val.GoodsId,
			SkuId:    val.SkuId,
			Price:    strconv.FormatInt(val.Price, 10),
			Quantity: val.Quantity,
		})
		skuId = val.SkuId
	}

	//skuId 查询秒杀商品详情
	detail, err := spikes.GetSpikesGoodsDetail(&pb.GetSpikesGoodsDetailRequest{
		SkuID:            skuId,
		SpikesActivityID: data.UpdateStock.SpikesActivityID,
	})

	if err != nil {
		return "", fmt.Errorf("spikes服务器错误:::%v", err)
	}
	//判断商品库存
	if detail.GetIn().SpikesStock < data.UpdateStock.Num {
		return "", fmt.Errorf("商品库存不足:::%v", err)
	}
	//计算秒杀价格
	price, err := strconv.ParseFloat(detail.GetIn().SpikesPrice, 2)
	sum := price * float64(data.UpdateStock.Num)

	//生成订单号
	no := uuid.NewString()
	//传参
	oo := &orderpb.OrderInfo{
		OrderNo:        no,
		PayType:        data.PayType,
		AddressId:      data.AddressId,
		UserId:         data.UserId,
		CouponId:       data.CouponId,
		OrderGoodsInfo: pr,
		Amount:         float32(sum),
	}
	fmt.Println("接收到的：：；", oo)

	//创建订单
	orderReq := &orderpb.CreateOrderRequest{In: oo} // 订单请求体

	//扣减库存
	SpikesReq := &pb.UpdateSpikesStockByGoodsIDRequest{
		GoodsID:          data.UpdateStock.GoodsID,
		SpikesActivityID: data.UpdateStock.SpikesActivityID,
		Num:              data.UpdateStock.Num,
	} // 库存请求体
	fmt.Println("接收到的：：；", SpikesReq)

	//事务id
	gid := uuid.NewString()
	//初始化 Saga 事务
	saga := dtmcli.NewSaga("121.36.228.151:36789", gid).
		Add("123.60.78.13:8036/order.Order/OrderCreation", "123.60.78.13:8036/order.Order/OrderCreation", orderReq).
		Add("121.36.228.151:4455/spikes.SpikesServer/UpdateSpikesStock", "121.36.228.151:4455/spikes.SpikesServer/RoUpdateSpikesStock", SpikesReq)
	err = saga.Submit()

	fmt.Println("事务数据：：", saga)
	return saga.Gid, err
}
